package cn.gov.msa.filter;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.filter.OncePerRequestFilter;

import cn.gov.msa.util.RepeatedlyReadRequestWrapper;

public class InputFilter extends OncePerRequestFilter {

	@Override
	public void destroy() {
	}

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
			throws ServletException, IOException {
			//获取请求的URL  
			String url = request.getRequestURI();
		 	if(url.indexOf("upload_fileinput.do")>=0){   //给文件上传放行，防止出错
	        	chain.doFilter(request, response);  
	        	return;
	        }
			RepeatedlyReadRequestWrapper requestWrapper = null;
			  String  param = null;
			if ("POST".equals(request.getMethod().toUpperCase())){
				requestWrapper = new RepeatedlyReadRequestWrapper( request);
	            param =  requestWrapper.getBodyString(requestWrapper);
			}else {
				param = request.getQueryString();	
			}
		    String regEx="<[^>]+>"; 
		    if(null!=param && !"".equals(param.trim())) {
				Pattern pattern = Pattern.compile(regEx);
				Matcher matcher = pattern.matcher(param);
				System.err.println("匹配结果："+matcher.find());
				if(!matcher.find()) {
					if(null ==requestWrapper) {
						chain.doFilter(request, response);
					}else {
					 chain.doFilter(requestWrapper, response);
					}
				}else {
					response.setCharacterEncoding("UTF-8");
		            response.getWriter().write("{\"result\":\"0\",\"info\":\"输入字段包含特殊字符\"}");
				} 
		    }else {
		    	chain.doFilter(request, response);
		    }
	}
}
